<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */

namespace App\Api\Controllers\Auths;

use App\Api\BaseApi;
use App\Models\AdvanceCard;
use App\Models\AdvanceCardSetting;
use App\Models\GroupOrderBatche;
use App\Models\GroupOrderProduct;
use App\Models\GroupOrderSession;
use App\Models\GroupOrderSetting;
use App\Models\GroupShipment;
use App\Models\UserAddress;
use App\Service\Group\BatchOrderService;
use App\Service\Setting\BeanSettingService;
use App\Service\Setting\GroupSettingService;
use App\Service\User\BeanAccountService;
use App\Service\User\PerformanceService;
use App\Service\User\PointAccountServices;
use App\Service\User\VoucherPackageService;
use App\Service\User\WalletAccountService;

class GroupApi extends BaseApi
{
    public function _groupBuyingOrder()
    {
        $request = self::validate([
            'group_session_id' => 'required',
            'group_product_id' => 'required',
            'number' => 'required|min:1',
            'is_make_an_appointment' => 'required|in:1,2',
            'advance_card_id' => 'required',
        ]);
        $makeAnAppointment = $request->get('is_make_an_appointment');
        $number = $request->get('number');
        $user = self::UserModel(['userLevel', 'address']);
        $gos = GroupOrderSetting::query()->first();
        if ($gos->pre_sale == 0 && $request->get('is_make_an_appointment') == 1) {
            return responses('未开启预约拼单！拼单失败', 7);
        }

//        $this->transaction_password($user);
        $groupProduct = GroupOrderProduct::query()->find($request['group_product_id']);
        $groupSession = GroupOrderSession::query()
            ->where('date', now()->format('Y-m-d'))
            ->find($request['group_session_id']);

        if (blank($groupProduct)) {
            return responses('无效的商品', 7);
        }
        if ($groupSession->isActive() != 1 && $makeAnAppointment == 2) {
            return responses('当前拼团场次未开启！', 7);
        }
        if ($makeAnAppointment == 1) {
            if ($groupSession->isActive() == 3) {
                return responses('拼团场次已结束！', 7);
            }
        }
        $advance_card = null;
        if ($request->get('advance_card_id', null)) {
            $advance_card = AdvanceCard::query()
                ->where('id', $request->get('advance_card_id'))
                ->where('user_id', self::UserId())
                ->where('voucher', '>', 0)
                ->where('deposit_amount', '>', 0)
                ->where('status', 2)
                ->first();
            if (blank($advance_card)) {
                return responses('没有可用的保证金或代金券', 7);
            }
            $setting = AdvanceCardSetting::query()->first();
            if ($advance_card->deposit_amount < $groupProduct->price) {
                return responses(sprintf('保证金小于%s,拼团失败', $setting->guarantee_fund), 7);
            }

            if ($advance_card->voucher < bcmul($groupProduct->price, $number, 2)) {
                return responses('代金券不足', 7);
            }
        } else {
            $productPrice = $groupProduct->price;
            $productPrice = bcmul($productPrice, $number, 2);
            $setting = BeanSettingService::make()->getSetting();
            $paymentBean = bcdiv($productPrice, $setting['PRICE'], 2); //KC通证价格换算
            $bean = bcmul($paymentBean, $setting['PAYMENT'], 2); //支付总价百分比的数量 unit_price burn

            if (BeanAccountService::make()->checkTheBalance($user->id) < $bean) {
                return responses('KC通证余额不足！', 7);
            }
            if (WalletAccountService::make()->checkTheBalance($user->id) < $productPrice) {
                return responses('钱包余额不足！', 7);
            }
        }
        $res = BatchOrderService::make($user->id)->processOrder(
            $user->id,
            $groupSession->id,
            $groupProduct->price,
            $number,
            $advance_card
        );
//        $lastGroupOrder = GroupOrder::query()
//            ->where('user_id', $user->id)
//            ->latest('id')
//            ->first();
//        $gps = GroupService::make();
//
//        for ($i = 0; $i < $number; ++$i) {
//            $lastGroupOrder = $gps->createAGroupBuyingOrder(
//                $user,
//                $groupSession,
//                $groupProduct,
//                $makeAnAppointment,
//                1,
//                $advance_card,
//                $lastGroupOrder
//            );
//        }
        return responses($res);
    }

    public function groupOrderLists()
    {
        $request = self::validate([
            'type' => 'required|in:1,2,3,4',
        ]);
        switch ($request['type']) {
            case 2:
                //
                $res = GroupOrderBatche::with(['product'])
                    ->where('user_id', self::UserId())
                    ->where('type', 2)
                    ->where('status', 1)
                    ->latest('end_date')
                    ->get();
                break;
            case 3:
                $res = GroupOrderBatche::with(['product'])
                    ->where('user_id', self::UserId())
                    ->where('type', 1)
                    ->where('status', 1)
                    ->latest('end_date')
                    ->get();
                break;
            case 4:
                $res = GroupOrderBatche::with(['product'])
                    ->where('user_id', self::UserId())
                    ->where('for_sale',1)
                    ->latest('end_date')
                    ->get();
                break;
            default:
                $res = GroupOrderBatche::with('product')
                    ->where('user_id', self::UserId())
                    ->latest('id')
                    ->get();
        }

        return responses($res);
    }

    public function groupBuyingOrder()
    {
        $request = self::validate([
            'group_product_id' => 'required',
        ]);
        $now = now();
        $start = now()->setTime(7, 0, 0);
        $end = now()->setTime(22, 0, 0);

        if ($now->lt($start)) {
            return responses('当前拼团还未开始,请耐心等候', 7);
        }
        if ($now->gte($end)) {
            return responses('当前拼团已结束,请耐心等候明日7点开场', 7);
        }

        $user = self::UserModel();
        $this->transaction_password($user);
        $gos = GroupOrderSetting::query()->first();
        $groupProduct = GroupOrderProduct::query()->find($request['group_product_id']);
        $payBean = BeanSettingService::make()->getSetting('PAYMENT');
        if (blank($groupProduct)) {
            return responses('无效的商品', 7);
        }
        if (BeanAccountService::make()->checkTheBalance($user->id) < $payBean) {
            return responses('KC通证余额不足！', 7);
        }
        if (WalletAccountService::make()->checkTheBalance($user->id) < $groupProduct->price) {
            return responses('余额不足！', 7);
        }
        $count = GroupOrderBatche::query()
            ->where('group_date', now()->toDateString())
            ->where('user_id', $user->id)
            ->count('id');
        if ($count >= $gos->daily_group_limit) {
            return responses('今日拼单次数已用完！', 7);
        }

        $groupOrderBatches = GroupOrderBatche::query()
            ->where('user_id', $user->id)
            ->latest('id')
            ->first();
        $batch = $groupOrderBatches->batch ?? 0;
        if ($batch == count($gos->winning_settings)) {
            $batch = 1;
            $nextWinningSetting = $gos->winning_settings[0];
        } else {
            ++$batch;
            $nextWinningSetting = $gos->winning_settings[$batch - 1];
        }
        $min = 15;
        $max = 66;
        $type = $nextWinningSetting['type'];
        if ($type == 1) {
            $reward_amount = $nextWinningSetting['number'];
        } else {
            $reward_amount = 0;
        }
        $res = GroupOrderBatche::query()
            ->where('user_id', $user->id)
            ->create([
                'group_date' => now()->toDateString(),
                'end_date' => now()->addMinutes(rand($min, $max))->format('Y-m-d H:i'),
                'user_id' => $user->id,
                'product_id' => $groupProduct->id,
                'batch' => $batch,
                'type' => $type,
                'reward_amount' => $reward_amount,
                'status' => 0
            ]);
        VoucherPackageService::make()->recharge($user->id,$groupProduct->price); #发券
//
//        $userAddress = UserAddress::query()
//            ->select('id')
//            ->where('user_id', $user->id)
//            ->where('is_default', 1)
//            ->first();
//        GroupShipment::query()->create([
//            'user_id' => $user->id,
//            'user_address_id' => $userAddress->id ?? 0,
//            'remark' => '拼单成功,创建发货单',
//            'status' => 0,
//            'order_type' => 1,
//            'product_id'=> $groupProduct->id
//        ]);
        if ($res) {
            BeanAccountService::make()->consumption($user->id, $payBean, '拼团燃烧通证:'.$payBean);
            WalletAccountService::make()->consumption($user->id, $groupProduct->price, '拼团余额支付' . $groupProduct->price);
            BeanSettingService::make()->increaseTheAmountOfCombustion($payBean);
            PerformanceService::make()->userTreeRevenue($user, $groupProduct->price, 2); //团队收益
            PerformanceService::make()->performanceReward($user, $groupProduct->price, 2); //业绩奖励
            $setting = GroupSettingService::make()->getSetting();
            $contribution_value = $setting['contribution_value'];
            $user->increment('contribution_value', $contribution_value);
            return responses('拼单成功');
        }
        return responses('系统错误', 7);
    }

    public function consignmentOfGoods()
    {
        $request = self::validate([
            'type' => 'required|in:1,3',
            'group_id' => 'required',
        ]);
        $now = now();
        $start = now()->setTime(7, 0, 0);
        $end = now()->setTime(22, 0, 0);
        if ($now->lt($start)) {
            return responses('当前正在结算中,请耐心等候明日6点寄售', 7);
        }
        if ($now->gte($end)) {
            return responses('当前正在结算中,请耐心等候明日6点寄售', 7);
        }

        $group_id = $request->get('group_id');
        $type = $request->get('type');
        $gb = GroupOrderBatche::query()
            ->where('user_id', self::UserId())
            ->where('status', 1)
            ->where('type', 1)
            ->where('for_sale', 0)
            ->where('id', $group_id)
            ->first();
        if (blank($gb)) {
            return responses('无效的团购订单', 7);
        }
        if ($type == 1) {
            $setting = GroupOrderSetting::query()->first();
            $pointSalf = $setting->points_for_sale;
            if ($pointSalf > 0) {
                $point = PointAccountServices::make()->consumption(self::UserId(), $pointSalf, '挂售消耗积分:' . $pointSalf, 2);
                if (!$point) {
                    return responses('积分不足,挂售失败', 7);
                }
            }
        }
        if ($type == 3) {
            $userAddress = UserAddress::query()
                ->select('id')
                ->where('user_id', self::UserId())
                ->where('is_default', 1)
                ->first();
            GroupShipment::query()->create([
                'user_id' => self::UserId(),
                'user_address_id' => $userAddress->id ?? 0,
                'remark' => '放弃挂售,选择提货',
                'status' => 0,
                'order_type' => 2,
                'product_id'=> $gb->product_id
            ]);
        }
        $gb->for_sale = $type;
        $gb->save();

        return responses('操作成功');
    }

}
